package com.gupao.javavip.concurrent.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

public class ReentrantLockDemo {
    private static volatile long COUNT = 0;
    private static volatile AtomicInteger COUNT_A = new AtomicInteger(0);

    private static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) throws InterruptedException {
        test1();
        TimeUnit.SECONDS.sleep(3);
        System.out.println("=========" + COUNT);
    }

    private static void test1() {
        for (int i = 0; i < 2000; i++) {
            Thread thread = new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(1000);

                    COUNT++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
        }
    }

    private static void test2() {
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(() -> {
                try {
                    lock.lock();
                    COUNT++;
                    System.out.println(Thread.currentThread().getName() + "=>" + COUNT);
                } finally {
                    lock.unlock();
                }
            }, "Thread_" + i);
            thread.start();
        }
        System.out.println("=========" + COUNT);
    }

    private static void test3() throws InterruptedException {
        for (int i = 0; i < 100; i++) {
            Thread thread = new Thread(() -> {
                try {
                    TimeUnit.MILLISECONDS.sleep(100L);

                    lock.lock();
                    COUNT++;
                    System.out.println(COUNT);
                    System.out.println("A_" + COUNT_A.incrementAndGet());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            });
            thread.start();
        }
        System.out.println("=========" + COUNT);
    }
}
